package com.lineage.data.event;

import com.lineage.data.EventClass;
import com.lineage.data.cmd.CreateNewItem;
import com.lineage.data.executor.EventExecutor;
import com.lineage.server.datatables.ItemTable;
import com.lineage.server.datatables.RecordTable;
import com.lineage.server.model.Instance.L1PcInstance;
import com.lineage.server.serverpackets.S_SystemMessage;
import com.lineage.server.serverpackets.ServerBasePacket;
import com.lineage.server.templates.L1Event;
import com.lineage.server.thread.GeneralThreadPool;
import com.lineage.server.world.World;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Iterator;
import java.util.List;
import java.util.TimerTask;
import java.util.concurrent.ScheduledFuture;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class RandomGiftSet extends EventExecutor {
  private static final Log _log = LogFactory.getLog(RandomGiftSet.class);
  
  private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
  
  public static int TIME_DELAY;
  
  public static int BROADCAST_TIME_DELAY;
  
  public static int TOTAL_COUNT;
  
  public static int GIFT_ID;
  
  public static int GIFT_COUNT;
  
  public static int Level;
  
  public static EventExecutor get() {
    return new RandomGiftSet();
  }
  
  public void execute(L1Event event) {
    try {
      String[] set = event.get_eventother().split(",");
      TIME_DELAY = Integer.parseInt(set[0]);
      BROADCAST_TIME_DELAY = Integer.parseInt(set[1]);
      TOTAL_COUNT = Integer.parseInt(set[2]);
      GIFT_ID = Integer.parseInt(set[3]);
      GIFT_COUNT = Integer.parseInt(set[4]);
      Level = Integer.parseInt(set[5]);
      long now_time = System.currentTimeMillis();
      if (event.get_next_time() == null) {
        event.set_next_time(new Timestamp(now_time + (TIME_DELAY * 60 * 1000)));
        EventClass.get().updateEventNextTime(event.get_eventid(), event.get_next_time());
      } else {
        while (event.get_next_time().getTime() < now_time)
          event.set_next_time(
              new Timestamp(event.get_next_time().getTime() + (TIME_DELAY * 60 * 1000))); 
        EventClass.get().updateEventNextTime(event.get_eventid(), event.get_next_time());
      } 
      GetItemTimer getItemTimer = new GetItemTimer(event);
      getItemTimer.start();
    } catch (Exception e) {
      _log.error(e.getLocalizedMessage(), e);
    } 
  }
  
  private class GetItemTimer extends TimerTask {
    private ScheduledFuture<?> _timer;
    
    private L1Event _event;
    
    private List<L1PcInstance> _allPc;
    
    private GetItemTimer(L1Event event) {
      this._event = event;
    }
    
    private GetItemTimer(L1Event event, List<L1PcInstance> allPc) {
      this._event = event;
      this._allPc = allPc;
    }
    
    private void start() {
      int timeMillis = 60000;
      this._timer = GeneralThreadPool.get().scheduleAtFixedRate(this, 60000L, 60000L);
    }
    
    public void run() {
      try {
        if (this._allPc != null) {
          Iterator<L1PcInstance> iterator = this._allPc.iterator();
          while (iterator.hasNext()) {
            L1PcInstance pc = iterator.next();
            if (pc.getLevel() >= RandomGiftSet.Level && !pc.isGm()) {
              Thread.sleep(5000L);
              World.get()
                .broadcastPacketToAll((ServerBasePacket)new S_SystemMessage("\\aE恭喜玩家[" + pc.getName() + "]获得" + 
                    ItemTable.get().getTemplate(RandomGiftSet.GIFT_ID).getNameId() + "x" + 
                    RandomGiftSet.GIFT_COUNT));
              RecordTable.get().rangiveitem(pc.getName());
              CreateNewItem.createNewItem(pc, RandomGiftSet.GIFT_ID, RandomGiftSet.GIFT_COUNT);
            } 
          } 
          this._allPc = null;
        } 
        long now_time = System.currentTimeMillis();
        if (this._event.get_next_time().getTime() < now_time) {
          this._allPc = World.get().getRandomPlayers(RandomGiftSet.TOTAL_COUNT);
          if (this._allPc == null || this._allPc.size() < RandomGiftSet.TOTAL_COUNT)
            return; 
          this._event.set_next_time(new Timestamp(
                this._event.get_next_time().getTime() + (RandomGiftSet.TIME_DELAY * 60 * 1000)));
          EventClass.get().updateEventNextTime(this._event.get_eventid(), this._event.get_next_time());
          World.get().broadcastPacketToAll(
              (ServerBasePacket)new S_SystemMessage("\\aD即将随机抽奖，将随机抽出线上玩家获得奖励"));
        } else if ((this._event.get_next_time().getTime() - now_time) / 
          60000L <= RandomGiftSet.BROADCAST_TIME_DELAY && (
          this._event.get_next_time().getTime() - now_time) % 3600000L == 0L) {
          World.get().broadcastPacketToAll((ServerBasePacket)new S_SystemMessage("\\aD下次送礼抽奖时间为[" + RandomGiftSet
                .sdf.format(this._event.get_next_time()) + "]\n随机抽出线上玩家获得奖励"));
        } 
      } catch (Exception e) {
        RandomGiftSet._log.error("随机送礼系统时间轴异常重启", e);
        GeneralThreadPool.get().cancel(this._timer, false);
        GetItemTimer getItemTimer = new GetItemTimer(this._event, this._allPc);
        getItemTimer.start();
      } 
    }
  }
}
